package com.taxshare.purchaser.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.entity.ApplicationRecordDetailEntity;
import com.taxshare.purchaser.entity.ApplicationRecordEntity;
import com.taxshare.purchaser.entity.TrainTicketEntity;
import com.taxshare.purchaser.entity.TrainTicketPoolEntity;
import com.taxshare.purchaser.mapper.ApplicationRecordDetailMapper;
import com.taxshare.purchaser.mapper.ApplicationRecordMapper;
import com.taxshare.purchaser.mapper.TrainTicketMapper;
import com.taxshare.purchaser.mapper.TrainTicketPoolMapper;
import com.taxshare.purchaser.view.dto.TrainTicketDtO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author YANG
 * @date 2021/4/9
 * @Description:火车票采集
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class TrainTicketCollectService extends ServiceImpl<TrainTicketMapper, TrainTicketEntity> {

    private static String timeStart = " 00:00:00";
    private static String timeEnd = " 23:59:59";

    @Autowired
    TrainTicketPoolMapper trainTicketPoolMapper;

    @Autowired
    ApplicationRecordDetailMapper applicationRecordDetailMapper;

    @Autowired
    ApplicationRecordMapper applicationRecordMapper;

    /**
     * 火车票查询【发票采集】
     *
     * @param query
     * @return
     */
    public Response queryTrainTicket(PageRequest<TrainTicketDtO> query) {
        QueryWrapper<TrainTicketEntity> trainQuery = new QueryWrapper<>();
        TrainTicketDtO trainTicketDtO = query.getInfo();
        String createTimeStrStart = trainTicketDtO.getCreateTimeStrStart();
        String createTimeStrEnd = trainTicketDtO.getCreateTimeStrEnd();
        String selectFlag = trainTicketDtO.getSelectFlag();
        if (StrUtil.isNotBlank(trainTicketDtO.getInvoiceNo())) {
            trainQuery.eq("invoice_no", trainTicketDtO.getInvoiceNo());
        }
        if (StrUtil.isNotBlank(createTimeStrStart) && StrUtil.isNotBlank(createTimeStrEnd)) {
            trainQuery.between("create_time_str", createTimeStrStart + timeStart, createTimeStrEnd + timeEnd);
        }
        //权限处理
        if(StrUtil.isNotBlank(UserInfoUtil.getUserID())){
            if(CodeConstant.GENERAL_TYPE.equals(UserInfoUtil.getUserType())){
                trainQuery.and((invoice ->
                        invoice.eq("person_liable_id", UserInfoUtil.getUserID())//责任人
                            .or().eq("collector_id", UserInfoUtil.getUserID())//采集人
                                .or().like("licensee_id", UserInfoUtil.getUserID())));//被授权人
            }
        }
        //查询页面判断标志 采集页面查询传1，未报销传2，已报销传3
        if (StrUtil.isNotBlank(selectFlag)) {
            if (CodeConstant.FLAG_WBX.equals(selectFlag)) {
                trainQuery.in("reimbursement_status", CodeConstant.NOT_REIMBURSEMENT);
            } else if (CodeConstant.FLAG_YBX.equals(selectFlag)) {
                trainQuery.eq("reimbursement_status", CodeConstant.REIMBURSEMENT_2);
            } else if (CodeConstant.FLAG_FPCJ.equals(selectFlag)) {
                if (StrUtil.isNotBlank(trainTicketDtO.getReimbursementStatus())) {
                    trainQuery.eq("reimbursement_status", trainTicketDtO.getReimbursementStatus());
                }
            }
        } else {
            return Response.error("PUR_107");
        }
        trainQuery.orderByDesc("create_time");
        IPage<TrainTicketEntity> trainTicketEntityIPage = PageHelp.siamplePage(this, trainQuery, query.getPage(), TrainTicketEntity.class);
        return Response.success(trainTicketEntityIPage);
    }

    /**
     * 火车票删除【发票采集】
     *
     * @param trainTicketDtO
     * @return
     */
    public Response trainTicketDelete(TrainTicketDtO trainTicketDtO) {
        List<String> uuidList = trainTicketDtO.getUuidList();
        if (CollUtil.isNotEmpty(uuidList)) {
            QueryWrapper<TrainTicketEntity> trainQuery = new QueryWrapper<>();
            trainQuery.in("uuid", uuidList);
            trainQuery.eq("reimbursement_status", CodeConstant.REIMBURSEMENT_2);
            if (baseMapper.selectCount(trainQuery) > 0) {
                return Response.error("PUR_103");
            }
            baseMapper.delete(new QueryWrapper<TrainTicketEntity>().in("uuid", uuidList));
        } else {
            return Response.error("PUR_201");
        }
        return Response.success();
    }

    /**
     * 责任人、记账科目、授权报销设置【未报销】
     *
     * @param trainTicketDtO
     * @return
     */
    public Response personLiable(TrainTicketDtO trainTicketDtO) {
        String updateFlag = trainTicketDtO.getUpdateFlag();
        TrainTicketEntity trainTicketEntity = new TrainTicketEntity();
        if (StrUtil.isNotBlank(updateFlag)) {
            //责任人设置
            if (CodeConstant.FLAG_ZRR.equals(updateFlag)) {
                trainTicketEntity.setPersonLiable(trainTicketDtO.getPersonLiable());
                trainTicketEntity.setPersonLiableId(trainTicketDtO.getPersonLiableId());
            } else if (CodeConstant.FLAG_JZKM.equals(updateFlag)) {
                //记账科目设置
                trainTicketEntity.setBookingAccount(trainTicketDtO.getBookingAccount());
            } else if (CodeConstant.FLAG_SQR.equals(updateFlag)) {
                //被授权人设置
                List<String> licenseeList = trainTicketDtO.getLicenseeList();
                List<String> licenseeIdList = trainTicketDtO.getLicenseeIdList();
                if (CollUtil.isNotEmpty(licenseeList) && CollUtil.isNotEmpty(licenseeIdList)) {
                    String licensee = licenseeList.stream().map(String::valueOf).collect(Collectors.joining(","));
                    String licenseeId = licenseeIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
                    trainTicketEntity.setLicensee(licensee);
                    trainTicketEntity.setLicenseeId(licenseeId);
                } else {
                    return Response.error("PUR_112");
                }
            }
            UpdateWrapper<TrainTicketEntity> trainUpdate = new UpdateWrapper<>();
            trainUpdate.in("uuid", trainTicketDtO.getUuidList());
            this.update(trainTicketEntity, trainUpdate);
        } else {
            return Response.error("PUR_107");
        }
        return Response.success();
    }

    /**
     * 提交报销【未报销】
     *
     * @param trainTicketDtO
     * @return
     */
    public Response submitReimbursement(TrainTicketDtO trainTicketDtO) {
        QueryWrapper<TrainTicketEntity> trainQuery = new QueryWrapper<>();
        List<String> uuidList = trainTicketDtO.getUuidList();
        trainQuery.in("uuid", uuidList);
        trainQuery.eq("reimbursement_status", CodeConstant.REIMBURSEMENT_1);
        List<TrainTicketEntity> trainTicketEntities = baseMapper.selectList(trainQuery);
        if (trainTicketEntities == null || trainTicketEntities.isEmpty() || uuidList.size() != trainTicketEntities.size()) {
            return Response.error("PUR_105");
        }
        for (TrainTicketEntity trainTicketEntity : trainTicketEntities) {
            TrainTicketPoolEntity trainTicketPoolEntity = new TrainTicketPoolEntity();
            BeanUtil.copyProperties(trainTicketEntity, trainTicketPoolEntity);
            trainTicketPoolEntity.setUuid(UUIDUitl.UUID32(false));
            trainTicketPoolEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_2);
            trainTicketPoolMapper.insert(trainTicketPoolEntity);
        }
        //将火车票采集表中对应发票的报销状态改为已报销
        trainTicketEntities.forEach(trainTicketEntity -> {
            trainTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_2);
            trainTicketEntity.setSubmitUserId(UserInfoUtil.getUserID());
        });
        this.updateBatchById(trainTicketEntities);
        return Response.success();
    }

    /**
     * 申请驳回【已报销】
     *
     * @param trainTicketDtO
     * @return
     */
    public Response applicationRejected(TrainTicketDtO trainTicketDtO) {
        List<String> uuidList = trainTicketDtO.getUuidList();
        List<TrainTicketEntity> trainTicketEntities = baseMapper.selectList(new QueryWrapper<TrainTicketEntity>().in("uuid", uuidList));
        if (trainTicketEntities == null || trainTicketEntities.isEmpty() || uuidList.size() != trainTicketEntities.size()) {
            return Response.error("PUR_110");
        }
        //生成申请单号
        String recordNo = UUIDUitl.UUID16(false);
        for (TrainTicketEntity trainTicketEntity : trainTicketEntities) {
            ApplicationRecordDetailEntity applicationRecordDetailEntity = new ApplicationRecordDetailEntity();
            applicationRecordDetailEntity.setUuid(UUIDUitl.UUID32(false));
            applicationRecordDetailEntity.setRecordNo(recordNo);
            applicationRecordDetailEntity.setInvoiceType(trainTicketEntity.getInvoiceType());
            applicationRecordDetailEntity.setInvoiceNo(trainTicketEntity.getInvoiceNo());
            applicationRecordDetailMapper.insert(applicationRecordDetailEntity);
        }
        ApplicationRecordEntity applicationRecordEntity = new ApplicationRecordEntity();
        applicationRecordEntity.setUuid(UUIDUitl.UUID32(false));
        applicationRecordEntity.setRecordNo(recordNo);
        applicationRecordEntity.setApplicationDate(trainTicketDtO.getApplicationDate());
        applicationRecordEntity.setApplicationReasons(trainTicketDtO.getApplicationReasons());
        applicationRecordEntity.setApplicationPerson(UserInfoUtil.getUserNickName());
        applicationRecordEntity.setApprovalStatus(CodeConstant.APPROVAL_1);
        applicationRecordEntity.setTicketTypes(CodeConstant.TICKET_HCP);
        applicationRecordMapper.insert(applicationRecordEntity);
        trainTicketEntities.forEach(trainTicketEntity -> {
            trainTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_5);
        });
        this.updateBatchById(trainTicketEntities);
        return Response.success();
    }


}
